<template>
    <div class="container">
        <div class="main">
            <div class="header">
                <el-button type="primary" @click="add">新建</el-button>
                <el-button type="success" @click="importData">导入</el-button>
                <el-button type="warning" @click="edit">编辑</el-button>
            </div>
            <el-table :data="tableData" border class="eltable">
                <el-table-column prop="rkzt" label="状态" width="120"></el-table-column>
                <el-table-column prop="wl_code" label="物料编码"></el-table-column>
                <el-table-column prop="wl_name" label="物料名称"></el-table-column>
                <el-table-column prop="dictionary_name" label="物料分类"></el-table-column>
                <el-table-column prop="ks_name" label="供应商"></el-table-column>
                <el-table-column prop="dw_name" label="物料单位"></el-table-column>
                <el-table-column prop="yclcgxq_ydhsl" label="到货数量"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                        <el-button type="text" @click="editRow(row)">入库</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="button-container">
                <el-button type="danger" @click="onCancel">返回</el-button>
            </div>
        </div>
    </div>

    <el-dialog v-model="dialogVisible" title="批量入库" width="800px">
        <el-form :model="form" class="demo-form-inline" :rules="rules" ref="formRef">
            <label for="warehouse">仓库</label>
            <el-row :gutter="27">
                <el-col :span="8">
                    <el-form-item label="所属仓库" :label-width="formLabelWidth" prop="kw_ssck">
                        <el-select v-model="form.kw_ssck" placeholder="请选择所属仓库" @change="handleWarehouseChange">
                            <el-option v-for="option in warehouseOptions" :key="option.value" :label="option.label"
                                :value="option.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="所属库区" :label-width="formLabelWidth" prop="kw_sskq">
                        <el-select v-model="form.kw_sskq" placeholder="请选择所属库区" @change="handleLocationChange">
                            <el-option v-for="option in locationOptions" :key="option.value" :label="option.label"
                                :value="option.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="所属库位" :label-width="formLabelWidth" prop="kw_sskw">
                        <el-select v-model="form.kw_sskw" placeholder="请选择所属库位">
                            <el-option v-for="option in positionOptions" :key="option.value" :label="option.label"
                                :value="option.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="物料数量" :label-width="formLabelWidth" prop="bz">
                        <el-input v-model="form.rks" placeholder="请输入物料数量"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
    setup() {
       // const userId = localStorage.getItem('userId');

        const router = useRouter();
        const route = useRoute();
        const row = ref(null);
        const searchKey = ref('');
        const treeData = ref([]);
        const defaultProps = {
            children: 'children',
            label: 'label',
        };

        const tableData = ref([]);

        const selectedFilter = ref('');
        const searchTable = ref('');
        const currentPage = ref(1);
        const pageSize = ref(2);
        const totalItems = ref(3);
        const dialogVisible = ref(false);
        const form = ref({
            kw_ssck: '', // 所属仓库
            kw_sskq: '', // 所属库区
            kw_sskw: '', // 所属库位
            rks: '' // 物料数量
        });
        const warehouseOptions = ref([]);
        const locationOptions = ref([]);
        const positionOptions = ref([]);




        const sx1 = (row) => {
            axios.get('/api/Rm_yclcgxq/Getrk?code=' + row)
                .then(function (response) {
                    console.log(response.data);
                    tableData.value = response.data
                })
                .catch(function (error) {
                    console.error('错误:', error);
                })
        }

        // 获取仓库数据（下拉框）
        const fetchWarehouseOptions = async () => {
            try {
                const response = await axios.get('/api/Wbd_ck/Wbd_Ck');
                console.log(response.data);
                warehouseOptions.value = response.data.map(item => ({
                    label: item.ck_name, // 假设返回的数据中仓库名称字段为 name
                    value: item.ck_code    // 假设返回的数据中仓库 ID 字段为 id
                }));
            } catch (error) {
                console.error('获取仓库数据失败:', error);
            }
        };
        // 获取库区数据（下拉框）
        const fetchLocationOptions = async (ck_code) => {
            try {
                const response = await axios.get('/api/Wbd_kq/Getcode?code=' + ck_code);
                locationOptions.value = response.data.map(item => ({
                    label: item.kq_name,
                    value: item.kq_code
                }));
            } catch (error) {
                console.error('获取库区数据失败:', error);
            }
        };
        // 获取库位数据（下拉框）
        const fetchPositionOptions = async (kq_code) => {
            console.log(kq_code);
            try {
                const response = await axios.get('/api/Wbd_kw/Getkw?code=' + kq_code);
                console.log(response.data);
                positionOptions.value = response.data.map(item => ({
                    label: item.kw_name,
                    value: item.kw_code
                }));
            } catch (error) {
                console.error('获取库位数据失败:', error);
            }
        };
        const handleWarehouseChange = (ck_code) => {
            // 清空库区和库位选择
            form.value.kq_name = '';
            form.value.kw_name = '';
            locationOptions.value = [];
            positionOptions.value = [];

            // 获取库区数据
            if (ck_code) {
                fetchLocationOptions(ck_code);
            }
        };
        // 处理库区选择变化
        const handleLocationChange = (kq_code) => {
            // 清空库位选择
            form.value.kw_name = '';
            positionOptions.value = [];

            // 获取库位数据
            if (kq_code) {
                fetchPositionOptions(kq_code);
            }
        };
        const submitForm = async () => {
            if (form.value.rks > form.value.yclcgxq_ydhsl) {
                 ElMessage.error("入库数量不能大于到货数量");
                return;
            } else {
                console.log(row.value);
                console.log(form.value);
    
                const response = await axios.get('/api/WMS_KC/GetWMS_KCDHDL?ck_code=' + form.value.kw_ssck + '&kq_code=' + form.value.kw_sskq + '&kw_code=' + form.value.kw_sskw + '&wl_code=' + form.value.wl_code)
                console.log(response.data);
                if (response.data) {
                    try {
                        // 发起第一个请求
                        const response1 = await axios.post('/api/WMS_RK/PostWMS_RK', {
                            rk_type: row.value.rklx,
                            rk_code: row.value.rkcode,
                            ck_code: form.value.kw_ssck,
                            rk_fzr: 3,
                            rk_jhrksj: row.value.jhrktime,
                            create_by: sessionStorage.getItem('u'),
                        });
                        console.log(response1.data);

                        // 发起第二个请求
                        const response2 = await axios.post('/api/WMS_RKXX/PostWMS_RKXX', {
                            rk_code: row.value.rkcode,
                            wl_code: form.value.wl_code,
                            kq_code: response.data,
                            rkxx_wlmc: form.value.wl_name,
                            rkxx_wlsl: form.value.wl_fl,
                            rkxx_rksl: form.value.rks
                        });
                        console.log(response2.data);

                        // 发起第三个请求
                        const response3 = await axios.put(`/api/WMS_KC/UpdateWMS_KCXGSL?code=${response.data}&sl=${form.value.rks}`);
                        console.log(response3.data);

                        // 如果所有请求都成功，可在这里添加成功提示
                         ElMessage.success('所有请求成功！');
                    } catch (error) {
                        // 捕获任意一个请求的错误
                        console.error('错误:', error);
                         ElMessage.error('请求失败，请检查网络或联系管理员！');
                    }
                    console.log(row.value.rkcode);
                    const response4 = await axios.put('/api/Rm_yclcg/Uprkzt?code=' + row.value.rkcode)
                        .catch(function (error) {
                            console.error('错误:', error);
                        });
                    console.log(response4.data);
                    if (response4.data) {
                        router.push({ path: '/RawMaterialsStorage' });
                    }
                    else {
                        console.log('修改失败');
                    }
                } else {
                    const now = new Date();
                    const year = now.getFullYear();
                    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
                    const day = String(now.getDate()).padStart(2, '0'); // 补零

                    // 生成四位随机数
                    const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

                    // 拼接时间字符串和随机数
                    const formattedTime = `${year}${month}${day}`;
                    let id = `kc${formattedTime}${randomNumber}`;

                    try {
                        // 使用 Promise.all 来并行执行三个请求
                        const [response1, response2, response3] = await Promise.all([
                            axios.post('/api/WMS_RK/PostWMS_RK', {
                                rk_type: row.value.rklx,
                                rk_code: row.value.rkcode,
                                ck_code: form.value.kw_ssck,
                                rk_fzr: 3,
                                rk_jhrksj: row.value.jhrktime,
                                create_by: userId,
                            }),
                            axios.post('/api/WMS_RKXX/PostWMS_RKXX', {
                                rk_code: row.value.rkcode,
                                wl_code: form.value.wl_code,
                                kq_code: response.data,
                                rkxx_wlmc: form.value.wl_name,
                                rkxx_wlsl: form.value.wl_fl,
                                rkxx_rksl: form.value.rks
                            }),
                            axios.post('/api/WMS_KC/PostWMS_KC', {
                                kc_code: id,
                                ck_code: form.value.kw_ssck,
                                kq_code: form.value.kw_sskq,
                                kw_code: form.value.kw_sskw,
                                wl_code: form.value.wl_code,
                                ks_sl: form.value.rks
                            })
                        ]);

                        // 所有请求都成功后的处理
                        console.log(response1.data);
                        console.log(response2.data);
                        console.log(response3.data);

                        // 在这里可以继续执行其他操作
                    } catch (error) {
                        // 任何一个请求失败时的处理
                        console.error('错误:', error);
                    }
                }
            }
        };
        const onCancel = () => {
            router.push({ path: '/RawMaterialsStorage' });
        } 
        const add = () => {
            // 添加逻辑  
        };

        const edit = () => {
            // 编辑逻辑  
        };

        const importData = () => {
            // 导入逻辑  
        };

        const query = () => {
            // 查询逻辑  
            console.log('Querying with:', searchTable.value);
        };

        const editRow = (row) => {
            // 编辑行逻辑  
            console.log('Editing row:', row);
            dialogVisible.value = true;
            form.value = row;

        };

        const deleteRow = (row) => {
            // 删除行逻辑  
            console.log('Deleting row:', row);
        };

        const handleCurrentChange = (page) => {
            currentPage.value = page;
            // 分页逻辑  
            console.log('Current page:', page);
        };
        onMounted(() => {
            fetchWarehouseOptions();
            const rowData = route.query.row;
            if (rowData) {
                row.value = JSON.parse(rowData); // 反序列化 JSON 字符串
                console.log('Received row data:', row.value);
                console.log('Received row data:', row.value.yclcg_code);
            }
            sx1(row.value.yclcg_code);
        });


        // 确保所有函数都被返回  
        return {
            searchKey,
            treeData,
            defaultProps,
            tableData,
            selectedFilter,
            searchTable,
            currentPage,
            pageSize,
            totalItems,
            add,
            edit,
            importData,
            query,
            editRow,
            deleteRow,
            handleCurrentChange,
            dialogVisible,
            form,
            warehouseOptions,
            positionOptions,
            locationOptions,
            handleWarehouseChange,
            handleLocationChange,
            submitForm,
            row,
            onCancel
        };
    },
};
</script>

<style>
.container {
    display: flex;
    gap: 20px;
    height: 95%;
}

.sidebar {
    height: 100%;

}

.main {
    width: 80%;
    flex: 1;
    height: 100%;
}

.header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}

.eltable {
    height: 95%;
}

.letree {
    height: 100%;
}
.button-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
}
</style>